package com.situ.listview;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;
import java.util.concurrent.Future;

/**
 * Created by Gao on 2021/11/26.
 */

public class FruitAdapter extends ArrayAdapter<Fruit>{
    private static final String TAG = "FruitAdapter";
    private int resourceId;
    private List<Fruit> list;
    /**
     *
     * @param context 上下文，Activity这个对象就是上下文
     * @param resource fruit_item布局
     * @param objects  List<Fruit> list
     */
    public FruitAdapter(Context context, int resource, List<Fruit> objects) {
        super(context, resource, objects);
        resourceId = resource;
        list = objects;
    }

    /**
     *  完成数据和布局之间的绑定
     * @param position 正在渲染的位置，从0开始
     * @param convertView fruit_item这个布局
     * @param parent
     * @return
     */
    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.d(TAG, "getView: position:" + position);
        // Fruit fruit = getItem(position);
        Fruit fruit = list.get(position);

        /*if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        }
        ImageView fruitImage = (ImageView) convertView.findViewById(R.id.fruit_image);
        TextView fruitName = (TextView) convertView.findViewById(R.id.fruit_name);
        fruitImage.setImageResource(fruit.getImageId());
        fruitName.setText(fruit.getName());*/

        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            viewHolder.fruitImage = (ImageView) convertView.findViewById(R.id.fruit_image);
            viewHolder.fruitName = (TextView) convertView.findViewById(R.id.fruit_name);
            // 把ImageView和TextView缓存到convertView
            convertView.setTag(viewHolder);
        } else {
            // 直接从convertView中拿出来，不需要再重复findViewById的操作了
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());

        return convertView;
    }

    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    }


}
